package com.whmskj.xjlhbc.mobile.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.domain.Bchb07zjpbrbjl;
import com.whmskj.xjlhbc.mapper.Bchb07zjpbrbjlMapper;
import com.whmskj.xjlhbc.mobile.GetStartDate;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 坯布日报控制器
 * 表: BC-HB-07织机坯布日报记录 bchb07zjpbrbjl
 */
@RestController
@Tag(name = "坯布日报", description = "织机坯布日报记录接口")
@RequestMapping("/mobile/bchb07")
public class Bchb07Controller {

    @Autowired
    private Bchb07zjpbrbjlMapper bchb07zjpbrbjlMapper;

    /**
     * 获取坯布日报数据
     * 包含总体统计和按品号详细数据
     * 只查询当前盘存月内的数据
     */
    @GetMapping("/daily-report")
    @Operation(description = "获取坯布日报数据")
    public AjaxResult getDailyReport(@RequestParam(required = false) String date) {
        try {
            // 获取当前盘存月的日期范围
            String monthStartDateStr = GetStartDate.getMonthStartDate();
            LocalDate firstDayOfMonth = LocalDate.parse(monthStartDateStr.substring(0, 10));
            LocalDate lastDayOfMonth = firstDayOfMonth.plusMonths(1).withDayOfMonth(20);
            
            // 如果没有指定日期，使用当前盘存月内最新有数据的日期
            if (date == null || date.trim().isEmpty()) {
                date = getLatestDataDateInCurrentMonth();
            }
            
            // 验证指定日期是否在当前盘存月内
            if (date != null) {
                LocalDate queryDate = LocalDate.parse(date);
                if (queryDate.isBefore(firstDayOfMonth) || queryDate.isAfter(lastDayOfMonth)) {
                    return AjaxResult.error("查询日期不在当前盘存月范围内");
                }
            }
            
            if (date == null) {
                return AjaxResult.success("查询成功", createEmptyReport());
            }

            // 查询指定日期的数据
            LambdaQueryWrapper<Bchb07zjpbrbjl> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Bchb07zjpbrbjl::getStatisticsDate, date)
                   .orderByAsc(Bchb07zjpbrbjl::getNoNo);

            List<Bchb07zjpbrbjl> dataList = bchb07zjpbrbjlMapper.selectList(wrapper);

            Map<String, Object> result = new HashMap<>();
            
            // 总体统计
            Map<String, Object> summary = calculateSummary(dataList);
            result.put("summary", summary);
            
            // 详细数据列表
            List<Map<String, Object>> detailList = new ArrayList<>();
            for (Bchb07zjpbrbjl data : dataList) {
                Map<String, Object> detail = convertToDetailMap(data);
                detailList.add(detail);
            }
            result.put("detailList", detailList);
            
            // 查询日期
            result.put("queryDate", date);

            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取可用的日期列表
     * 只返回当前盘存月内的日期
     */
    @GetMapping("/available-dates")
    @Operation(description = "获取可用的日期列表")
    public AjaxResult getAvailableDates() {
        try {
            // 获取当前盘存月的日期范围
            String monthStartDateStr = GetStartDate.getMonthStartDate();
            LocalDate firstDayOfMonth = LocalDate.parse(monthStartDateStr.substring(0, 10));
            
            // 计算盘存月结束日期（下个月20号）
            LocalDate lastDayOfMonth = firstDayOfMonth.plusMonths(1).withDayOfMonth(20);
            
            LambdaQueryWrapper<Bchb07zjpbrbjl> wrapper = new LambdaQueryWrapper<>();
            wrapper.select(Bchb07zjpbrbjl::getStatisticsDate)
                   .between(Bchb07zjpbrbjl::getStatisticsDate, 
                           firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                           lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
                   .groupBy(Bchb07zjpbrbjl::getStatisticsDate)
                   .orderByDesc(Bchb07zjpbrbjl::getStatisticsDate);

            List<Bchb07zjpbrbjl> dateList = bchb07zjpbrbjlMapper.selectList(wrapper);
            
            List<String> dates = dateList.stream()
                    .map(Bchb07zjpbrbjl::getStatisticsDate)
                    .filter(Objects::nonNull)
                    .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);

            return AjaxResult.success("查询成功", dates);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取指定品号的详细数据
     */
    @GetMapping("/product-detail")
    @Operation(description = "获取指定品号的详细数据")
    public AjaxResult getProductDetail(@RequestParam String date, @RequestParam String productNo) {
        try {
            LambdaQueryWrapper<Bchb07zjpbrbjl> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Bchb07zjpbrbjl::getStatisticsDate, date)
                   .eq(Bchb07zjpbrbjl::getNoNo, productNo);

            Bchb07zjpbrbjl data = bchb07zjpbrbjlMapper.selectOne(wrapper);
            
            if (data == null) {
                return AjaxResult.error("未找到指定品号的数据");
            }

            Map<String, Object> result = convertToDetailMap(data);
            return AjaxResult.success("查询成功", result);
        } catch (Exception e) {
            return AjaxResult.error("查询失败: " + e.getMessage());
        }
    }

    /**
     * 获取最新有数据的日期
     */
    private String getLatestDataDate() {
        LambdaQueryWrapper<Bchb07zjpbrbjl> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Bchb07zjpbrbjl::getStatisticsDate)
               .orderByDesc(Bchb07zjpbrbjl::getStatisticsDate)
               .last("limit 1");

        Bchb07zjpbrbjl latestData = bchb07zjpbrbjlMapper.selectOne(wrapper);
        return latestData != null ? latestData.getStatisticsDate() : null;
    }

    /**
     * 获取当前盘存月内最新有数据的日期
     */
    private String getLatestDataDateInCurrentMonth() {
        // 获取当前盘存月的日期范围
        String monthStartDateStr = GetStartDate.getMonthStartDate();
        LocalDate firstDayOfMonth = LocalDate.parse(monthStartDateStr.substring(0, 10));
        LocalDate lastDayOfMonth = firstDayOfMonth.plusMonths(1).withDayOfMonth(20);
        
        LambdaQueryWrapper<Bchb07zjpbrbjl> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(Bchb07zjpbrbjl::getStatisticsDate)
               .between(Bchb07zjpbrbjl::getStatisticsDate, 
                       firstDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")),
                       lastDayOfMonth.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))
               .orderByDesc(Bchb07zjpbrbjl::getStatisticsDate)
               .last("limit 1");

        Bchb07zjpbrbjl latestData = bchb07zjpbrbjlMapper.selectOne(wrapper);
        return latestData != null ? latestData.getStatisticsDate() : null;
    }

    /**
     * 计算总体统计
     */
    private Map<String, Object> calculateSummary(List<Bchb07zjpbrbjl> dataList) {
        Map<String, Object> summary = new HashMap<>();
        
        if (dataList.isEmpty()) {
            summary.put("varietyCount", 0);
            summary.put("machineCount", 0);
            summary.put("dailyProduction", "0.00");
            summary.put("averageEfficiency", "0%");
            return summary;
        }

        // 品种数
        int varietyCount = dataList.size();
        
        // 开台数总和
        int totalMachineCount = dataList.stream()
                .mapToInt(data -> data.getKts() != null ? data.getKts() : 0)
                .sum();
        
        // 当日产量总和
        BigDecimal totalDailyProduction = dataList.stream()
                .map(data -> data.getDrcl() != null ? data.getDrcl() : BigDecimal.ZERO)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 平均效率
        double averageEfficiency = dataList.stream()
                .mapToDouble(data -> data.getEfficiency() != null ? data.getEfficiency().doubleValue() : 0.0)
                .average()
                .orElse(0.0);

        summary.put("varietyCount", varietyCount);
        summary.put("machineCount", totalMachineCount);
        summary.put("dailyProduction", formatNumber(totalDailyProduction));
        summary.put("averageEfficiency", String.format("%.0f%%", averageEfficiency));

        return summary;
    }

    /**
     * 转换为详细数据Map
     */
    private Map<String, Object> convertToDetailMap(Bchb07zjpbrbjl data) {
        Map<String, Object> detail = new HashMap<>();
        
        detail.put("id", data.getId());
        detail.put("statisticsDate", data.getStatisticsDate());
        detail.put("productNo", data.getNoNo());
        detail.put("productName", data.getNameofpm());
        detail.put("weftDensity", formatNumber(data.getLatitude()));
        detail.put("machineCount", data.getKts());
        detail.put("dailyProduction", formatNumber(data.getDrcl()));
        detail.put("averagePerMachine", formatNumber(data.getTjz()));
        detail.put("standardizedProduction", formatNumber(data.getZbrcl()));
        detail.put("standardizedAverage", formatNumber(data.getZbtwcl()));
        detail.put("machineSpeed", formatNumber(data.getSpeed()));
        detail.put("efficiency", String.format("%.0f%%", data.getEfficiency() != null ? data.getEfficiency().doubleValue() : 0.0));
        detail.put("updater", data.getOtherOrganiser());
        detail.put("updateTime", data.getUpdateTime());

        return detail;
    }

    /**
     * 创建空报告
     */
    private Map<String, Object> createEmptyReport() {
        Map<String, Object> result = new HashMap<>();
        
        Map<String, Object> summary = new HashMap<>();
        summary.put("varietyCount", 0);
        summary.put("machineCount", 0);
        summary.put("dailyProduction", "0.00");
        summary.put("averageEfficiency", "0%");
        
        result.put("summary", summary);
        result.put("detailList", new ArrayList<>());
        result.put("queryDate", null);
        
        return result;
    }

    /**
     * 格式化数字
     */
    private String formatNumber(BigDecimal value) {
        if (value == null) {
            return "0.00";
        }
        return String.format("%.2f", value);
    }
}
